<template>
  <svg
    class="formula-content"
    overflow="visible"
    :width="box.w + 32"
    :height="box.h + 32"
    :stroke="'#000'"
    stroke-width="1"
    fill="none"
    stroke-linecap="round"
    stroke-linejoin="round"
  >
    <g :transform="`scale(${scale}, ${scale}) translate(0,0) matrix(1,0,0,1,0,0)`" transform-origin="0 50%">
      <path :d="pathd"></path>
    </g>
  </svg>
</template>

<script>
import Hfmath from './hfmath';

export default {
  props: {
    latex: {
      type: String,
      required: true,
    },
    width: {
      type: Number,
      required: true,
    },
    height: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      box: { x: 0, y: 0, w: 0, h: 0 },
      pathd: '',
    };
  },
  computed: {
    scale() {
      const boxW = this.box.w + 32;
      const boxH = this.box.h + 32;

      if (boxW > this.width || boxH > this.height) {
        if (boxW / boxH > this.width / this.height) return this.width / boxW;
        return this.height / boxH;
      }
      return 1;
    },
  },
  watch: {
    latex(newLatex) {
      this.updateEquation(newLatex);
    },
  },
  mounted() {
    this.updateEquation(this.latex);
  },
  methods: {
    updateEquation(latex) {
      const eq = new Hfmath(latex);
      this.pathd = eq.pathd({});
      this.box = eq.box({});
    },
  },
};
</script>

<style scoped>
svg {
  overflow: hidden;
}
</style>
